package com.ruiaa.meeting.utils;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.ruiaa.meeting.common.BusinessException;
import com.ruiaa.meeting.common.CommonResponse;
import com.ruiaa.meeting.common.ResponseCode;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author chenhuaiyi
 * @date 2022-11-04 20:38
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public CommonResponse<Object> handleBusinessException(BusinessException e){
        return CommonResponse.createForError(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public CommonResponse<Object> handleNotLoginException(NotLoginException e){
        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public CommonResponse<Object> handleNotRoleException(NotRoleException e){
        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResponse<Object> handleMissingServletRequestParameterException(MissingServletRequestParameterException e){
        return CommonResponse.createForError("请求参数有误");
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResponse<Object> handleConstraintViolationException(ConstraintViolationException e){
        return CommonResponse.createForError(e.getMessage());
    }
}
